import {compose, lifecycle, withHandlers, withState} from "recompose"
import {del, get, postJSON, postParam, putJSON, putParam} from "server"
import {HOST} from "../../../../shared/project-config"
import download from "libs/download"
import {message, Modal} from 'antd'
import React from "react"
import {rootPath} from "../../../../shared/init"
import { ExclamationCircleOutlined } from '@ant-design/icons'

const ViewType = {
  picture: 'picture',
  threeDimensional: '3d',
  video:'video'
}

const infoCompose = compose(
  withState('data', '$data', {
    favorite: true
  }),
  withState('checkedFiles', '$checkedFiles', []),
  withState('naviIndex', '$naviIndex', 0),
  //TODO:默认图片
  withState('picture', '$picture', undefined),
  withState('sizeData', '$sizeData', []),
  withState('sizeDataLoading', '$sizeDataLoading', false),
  //picture/3d
  withState('viewType', '$viewType', ViewType.picture),
  withHandlers({
    orderFeeCalc: ({data}) => {
      return (checkedFiles) => {
        const fee = (checkedFiles || [])
          .filter(i => !i['accessible'])
          .map(i => i.type === 'BOKE' ? data.cadPrice : data.pltPrice)
          .reduce((p, n) => p + n, 0)
        return `￥${(fee / 100).toFixed(2)}`
      }
    },
    onThumbSelect: ({$picture}) => {
      return (pic) => () => {
        $picture(pic.id)
      }
    },
    getInfo: ({$data, $picture, match}) => {
      return () => {
        const id = match.params.id
        get(`/clothing/${id}`, {})
          .then(res => {
            const images = res['pictureFiles']
            if (images && images.length > 0) {
              $picture(images[0].id)
            }
            $data(res)
          })
      }
    },
    onBack: ({history, preUrl}) => {
      return () => {
        history.push(preUrl || '/app/library')
      }
    },
    getSizeInfo: ({$sizeData, $sizeDataLoading, match}) => {
      return () => {
        $sizeDataLoading(true)
        const id = match.params.id
        console.info(id)
        get(`/size/clothing/${id}`)
          .then(data => $sizeData(data))
          .finally($sizeDataLoading(false))
      }
    },
    onViewTypeChange: ({$viewType}) => {
      return (event) => {
        $viewType(event.target.value)
      }
    },
    //选择文件
    onFileCheck: ({$checkedFiles, checkedFiles}) => {
      return (f) => (event) => {
        const checked = event.target.checked
        if (checked) {
          $checkedFiles(checkedFiles.concat(f))
        } else {
          $checkedFiles(checkedFiles.filter(i => i.id !== f.id))
        }
      }
    }
  }),
  withHandlers({
    //下载
    toDownload: ({history}) => {
      return (downloadFile) => () => {
        if (downloadFile['accessible'] === true) {
          download(`${HOST}/order/download?fileIds=${downloadFile.id}`)
        } else {
          const content = <div>当前文件需要购买后才能下载，确定要购买吗？</div>
          Modal.confirm({
            icon: <ExclamationCircleOutlined />,
            title: '购买确认',
            content: content,
            onOk: () => {
              postParam(`/order/create`, {fileIds: [downloadFile.id]})
                .then(data => {
                  history.push(`/${rootPath}/order/${data.id}`)
                })
            }
          })
        }
      }
    },
    //打包下载
    toBatchDownload: ({orderFeeCalc, history}) => {
      return (files) => () => {
        const haveNoPayFile = (files || []).some(f => !f['accessible'])
        const ids = files.map(f => f.id);
        if (haveNoPayFile) {
          const fee = orderFeeCalc(files)
          const content = (<div>
            当前文件列表有<b className={'line-stress'}>未购买</b>文件 <br/>
            需要支付 <b className={'line-stress red'}>{fee}</b> 元 <br/>
            确定要购买吗？</div>)
          Modal.confirm({
            icon: <ExclamationCircleOutlined />,
            title: '购买确认',
            content: content,
            onOk: () => {
              postParam(`/order/create`, {fileIds: ids})
                .then(data => {
                  history.push(`/${rootPath}/order/${data.id}`)
                })
            }
          })
        } else {
          download(`${HOST}/order/download?${ids.map(i => `fileIds=${i}`).join("&")}`)
        }
      }
    },
    addFavorite: ({$data, data}) => {
      return () => {
        postParam(`/favorite/${data.id}`, {})
          .then(res => {
            if (res.id) {
              data.favorite = true
              message.success(<span><b>{data.code}</b>收藏成功!</span>)
              $data(Object.assign({}, data))
            }
          })
      }
    },
    onMakeRequest: ({data}) => {
      return () => {
        postParam(`/order/makeRequest/submit`, {clothingId: data.id})
          .then((d) => message.success(<span>{d}</span>))
      }
    }
  }),
  lifecycle({
    componentDidMount() {
      const {getInfo, getSizeInfo} = this.props
      getInfo()
      getSizeInfo()
    }
  })
)

const titleCreate = (data) => {
  const {categories, title} = data
  if (title) return title
  if (!categories) return ''
  const styles = (categories.filter(c => c.type === 'style') || []).map(c => c.name).join('、')
  const types = (categories.filter(c => c.type === 'type') || []).map(c => c.name).join('、')
  const purposes = (categories.filter(c => c.type === 'purpose') || []).map(c => c.name).join('、')
  const peoples = (categories.filter(c => c.type === 'people') || []).map(c => c.name).join('、')
  const peopleText = peoples ? `,适合${peoples}` : ''
  const purposePrefix = peoples ? '出席' : ',适合'
  const purposeText = purposes ? `${purposePrefix}${purposes}` : ''
  return [styles ? styles + '风格' : '', types, peopleText, purposeText].filter(i => i).join('')
}

const sizeColumn = (params) => {
  return (params || []).filter((p, idx) => p.level === 'primary' || p.level === 'require' || idx === 0).map((p, idx) => {
    return idx === 0 ? {
      title: '尺码/部位',
      dataIndex: 'a',
      key: 'a'
    } : {
      title: p.displayName,
      dataIndex: p['columnName'].toLowerCase(),
      key: p['columnName'].toLowerCase()
    }
  })
}


export default infoCompose
export {titleCreate, sizeColumn, ViewType}